ServiceForm = {
	init : function(){
		var that = this;
		that.initAction();
	},
	
	initAction : function(){
		var that = this;
		//注册消息发送事件
		$(".service-main").on('click', '.do-send', function(){
			var message = $(".edit-area textarea").val().trim();
			if(message.length > 0){
				that.sendMessage(message);
				$(".edit-area textarea").val("");
			}
		});
	},
	
	/**
	 * 自己发送消息
	 */
	sendMessage : function(message){
		var that = this;
		serviceWebSocket.ws.send(message);
		
		var html = '<div class="message-one">';
		html += '<div class="message-self">';
		html += '<div class="message-title"><span>：</span><span>我</span></div>';
		html += '<div class="message-content"><span>' + message + '</span></div>';
		html += '</div></div>';
		$(".service-main .message").append($(html));
		that.formSetting();
	},
	
	/**
	 * 收到消息
	 */
	receiveMessage : function(userNick, message){
		var that = this;
		var html = '<div class="message-one">';
		html += '<div class="message-service">';
		html += '<div class="message-title"><span>' + userNick + '</span><span>：</span></div>';
		html += '<div class="message-content"><span>' + message + '</span></div>';
		html += '</div></div>';
		$(".service-main .message").append($(html));
		that.formSetting();
	},
	
	/**
	 * 设置滚动条和焦点
	 */
	formSetting : function(){
		$(".service-main .message").scrollTop( $(".service-main .message")[0].scrollHeight );
		$(".edit-area textarea").focus();
	}
}

/**
 * websocket类定义
 */
serviceWebSocket = {
	ws : null,
	init : function(){
		var that = this;
		ws = new WebSocket("ws://"+document.domain+":8282");
		ws.onopen = that.onopen;
		// 当有消息时根据消息类型显示不同信息
		ws.onmessage = that.onmessage; 
		ws.onclose = function() {
			console.log("连接关闭，定时重连");
			that.init();
		};
		ws.onerror = function() {
			console.log("出现错误");
		};
		that.ws = ws;
	},
	
	onopen : function(){
		console.log("start ws");
	},
	
	onmessage : function(message){
		var that = this;
		var data = eval("("+message.data+")");
        switch(data['type']){
            // 服务端ping客户端
            case 'ping':
                that.ws.send('{"type":"pong"}');
                break;;
            // 登录 更新用户列表
            case 'say':
                ServiceForm.receiveMessage(data['userNick'], data['content']);
                break;
            
        }
	}
}
$(function(){
	ServiceForm.init();
	serviceWebSocket.init();
})